# coding=utf-8

from flask import current_app
from app.close_ssh import close_ssh
from app.conn_ssh import conn_ssh
from app.get_task_datas import getMonthFirstDay, getCurrentMon, getLastYearMon
from config import config


def get_exec_result(ssh, command):
    current_app.logger.info("ssh :" + str(ssh))
    stdin, stdout, sterr = ssh.exec_command(command)
    sterrStr = str(sterr.read())
    stdoutStr = str(stdout.read())
    # close_ssh(ssh)
    return stdoutStr, sterrStr


# 手动输入命令执行
def execute_cmds(command):
    host = config['default'].CONNECT_SSH
    ssh = conn_ssh(host)

    stdoutStr, sterrStr = get_exec_result(ssh, command)
    if stdoutStr.strip():
        result = stdoutStr
    elif sterrStr.strip():
        result = sterrStr
    else:
        result = stdoutStr + sterrStr

    close_ssh(ssh)
    resultOut = ["[" + host[2] + "@" + host[0] + " ~]$ " + command, result]
    return resultOut


# 从账务处理获取S文件
def get_SFiles_From_ZWCL(command):
    host = config['default'].CONNECT_ZW_SSH
    ssh = conn_ssh(host)

    currentMonFirstDay = getMonthFirstDay()
    firstDayStr = currentMonFirstDay.strftime('%Y%m%d')
    current_app.logger.info(firstDayStr)

    commandStr = str(command[0][0] + firstDayStr + command[0][1])
    resultOut = [("[" + host[2] + "@" + host[0] + " ~]$ " + commandStr)]
    stdoutStr, sterrStr = get_exec_result(ssh, commandStr)
    if stdoutStr.strip():
        resultOut.append(stdoutStr)
    else:
        resultOut.append(sterrStr)
        return resultOut

    commandStr = str(command[0][2])
    resultOut = [("[" + host[2] + "@" + host[0] + " ~]$ " + commandStr)]
    stdoutStr, sterrStr = get_exec_result(ssh, commandStr)
    if stdoutStr.strip():
        if stdoutStr.strip() == '6':
            result = 'S文件目录重命名完成！'
            resultOut.append(stdoutStr)
            resultOut.append(result)
        else:
            result = 'S文件目录重命名失败，请检查！'
            resultOut.append(stdoutStr)
            resultOut.append(result)
            return resultOut
    else:
        result = sterrStr

    close_ssh(ssh)
    resultOut.append(result)
    return resultOut


# 启动S文件采集进程
def start_Xfer(command):

    # 连接主机
    host = config['default'].CONNECT_SSH
    ssh = conn_ssh(host)
    
    resultOut = []
    commandStr = str(command[1][0])
    resultOut.append("[" + host[2] + "@" + host[0] + " ~]$ " + commandStr)
    stdoutStr, sterrStr = get_exec_result(ssh, commandStr)
    if stdoutStr.strip():
        result = "进程号：" + stdoutStr.strip()
    else:
        result = sterrStr.strip()

    close_ssh(ssh)
    resultOut.append(result)
    return resultOut


# 检查S文件是否采集完成
def check_Xfer(command):

    # 连接主机
    host = config['default'].CONNECT_SSH
    ssh = conn_ssh(host)

    resultOut = []
    commandStr = str(command[2][0])
    resultOut.append("[" + host[2] + "@" + host[0] + " ~]$ " + commandStr)
    stdoutStr, sterrStr = get_exec_result(ssh, commandStr)
    if stdoutStr.strip():
        if stdoutStr.strip() == '6000':
            result = '已完成，个数：' + stdoutStr.strip()
        else:
            result = '未完成，个数：' + stdoutStr.strip()
    else:
        result = sterrStr.strip()

    close_ssh(ssh)
    resultOut.append(result)
    return resultOut


# 检查S文件是否正常
def check_SFiles(command):

    # 连接主机
    host = config['default'].CONNECT_SSH
    ssh = conn_ssh(host)

    currentMonFirstDay = getMonthFirstDay()
    firstDayStr = currentMonFirstDay.strftime('%Y%m%d')

    resultOut = []
    commandStr = str(command[3][0] + firstDayStr)
    resultOut.append("[" + host[2] + "@" + host[0] + " ~]$ " + commandStr)
    stdoutStr, sterrStr = get_exec_result(ssh, commandStr)
    if stdoutStr.strip():
        result = 'SFILE_DEST目录重命名完成'
        resultOut.append(result)
    else:
        result = sterrStr.strip()
        resultOut.append(result)
        return resultOut

    commandStr = str(command[3][1] + firstDayStr)
    resultOut.append("[" + host[2] + "@" + host[0] + " ~]$ " + commandStr)
    stdoutStr, sterrStr = get_exec_result(ssh, commandStr)
    if stdoutStr.strip():
        resultOut.append(stdoutStr)
    else:
        resultOut.append(sterrStr)

    close_ssh(ssh)
    return resultOut


# 停采集进程
def stop_Xfer(command):

    # 连接主机
    host = config['default'].CONNECT_SSH
    ssh = conn_ssh(host)

    resultOut = []
    commandStr1 = str(command[4][0])
    resultOut.append("[" + host[2] + "@" + host[0] + " ~]$ " + commandStr1)
    stdoutStr, sterrStr = get_exec_result(ssh, commandStr1)
    if stdoutStr.strip():
        if stdoutStr.strip() == '0':
            result = "采集进程已停止"
            resultOut.append(result)
        else:
            commandStr2 = str(command[4][1])
            resultOut.append("[" + host[2] + "@" + host[0] + " ~]$ " + commandStr2)
            stdoutStr2, sterrStr2 = get_exec_result(ssh, commandStr2)
            if stdoutStr2.strip():
                result2 = stdoutStr2.strip()
            else:
                result2 = sterrStr2.strip()
            resultOut.append(result2)
    else:
        result = sterrStr.strip()
        resultOut.append(result)

    close_ssh(ssh)
    return resultOut


# 备份批扣计算生成的文件
def bakupFiles(command):

    # 连接主机
    host = config['default'].CONNECT_SSH
    ssh = conn_ssh(host)

    currentMonFirstDay = getMonthFirstDay()
    firstDayStr = currentMonFirstDay.strftime('%Y%m%d')

    resultOut = []
    for i in range(0, 40):
        commandStr = str(command[i][0] + firstDayStr + command[i][1] + firstDayStr + command[i][2])
        current_app.logger.info("commandStr: " + commandStr)
        resultOut.append("[" + host[2] + "@" + host[0] + " ~]$ " + commandStr)
        stdoutStr, sterrStr = get_exec_result(ssh, commandStr)
        if stdoutStr.strip():
            result = "进程号：" + stdoutStr.strip()
        else:
            result = sterrStr.strip()

        resultOut.append(result)

    close_ssh(ssh)
    return resultOut


# 批扣计算日志检查
def WriteOffStartCalc(command):

    # 连接主机
    host = config['default'].CONNECT_SSH
    ssh = conn_ssh(host)

    commandStr = str(command[0])
    resultOut = [("[" + host[2] + "@" + host[0] + " ~]$ " + commandStr)]
    ssh.exec_command(commandStr)

    commandStr = str(command[1])
    resultOut.append("[" + host[2] + "@" + host[0] + " ~]$ " + commandStr)
    stdoutStr, sterrStr = get_exec_result(ssh, commandStr)
    if stdoutStr.strip():
        result = stdoutStr
    else:
        result = sterrStr

    close_ssh(ssh)
    resultOut.append(result)
    return resultOut


# 批扣文件平衡性检查
def checkFilesBalance(command):

    # 连接主机
    host = config['default'].CONNECT_SSH
    ssh = conn_ssh(host)

    currentMonFirstDay = getMonthFirstDay()
    firstDayStr = currentMonFirstDay.strftime('%Y%m%d')

    resultOut = []
    for i in range(0, 4):
        commandStr = str(command[i] + firstDayStr)
        resultOut.append("[" + host[2] + "@" + host[0] + " ~]$ " + commandStr)
        stdoutStr, sterrStr = get_exec_result(ssh, commandStr)
        if stdoutStr.strip():
            resultOut.append(stdoutStr)
            result = "ssh脚本已执行，请关注执行结果"
        else:
            result = sterrStr

        resultOut.append(result)
    close_ssh(ssh)
    return resultOut


# 批扣文件入库
def filesIndb(command):

    # 连接主机
    host = config['default'].CONNECT_SSH
    ssh = conn_ssh(host)

    currentMonFirstDay = getMonthFirstDay()
    firstDayStr = currentMonFirstDay.strftime('%Y%m%d')
    currentMon = getCurrentMon()
    lastYearMon = getLastYearMon()

    resultOut = []
    for i in range(0, 4):
        commandStr = str(command[i][0] + ' ' + firstDayStr + ' ' + currentMon + ' ' + lastYearMon)
        resultOut.append("[" + host[2] + "@" + host[0] + " ~]$ " + commandStr)
        stdoutStr, sterrStr = get_exec_result(ssh, commandStr)
        if stdoutStr.strip():
            result = stdoutStr
        else:
            result = sterrStr

        resultOut.append(result)

        commandStr = str(command[i][1] + ' ' + firstDayStr)
        resultOut.append("[" + host[2] + "@" + host[0] + " ~]$ " + commandStr)
        stdoutStr, sterrStr = get_exec_result(ssh, commandStr)
        if stdoutStr.strip():
            result = stdoutStr
        else:
            result = sterrStr

        resultOut.append(result)

        commandStr = str(command[i][2] + ' ' + firstDayStr + ' ' + currentMon)
        resultOut.append(commandStr)
        current_app.logger.info('filesIndb commandStr: %s', commandStr)
        stdoutStr, sterrStr = get_exec_result(ssh, commandStr)
        if stdoutStr.strip():
            result = stdoutStr
        else:
            result = sterrStr

        resultOut.append(result)
    close_ssh(ssh)
    return resultOut


# 批扣文件入库进程日志检查
def filesIndbCheck(command):

    # 连接主机
    host = config['default'].CONNECT_SSH
    ssh = conn_ssh(host)
    
    resultOut = []
    commandStr = str(command[0])
    ssh.exec_command(commandStr)
    resultOut.append("[" + host[2] + "@" + host[0] + " ~]$ " + commandStr)

    for i in range(1, 4):
        commandStr = str(command[i])
        resultOut.append("[" + host[2] + "@" + host[0] + " ~]$ " + commandStr)
        stdoutStr, sterrStr = get_exec_result(ssh, commandStr)
        if stdoutStr.strip():
            result = stdoutStr
        else:
            result = sterrStr

        resultOut.append(result)
    close_ssh(ssh)
    return resultOut


# 积分分拣结果验证
def SocreCalcFilter(command):

    # 连接主机
    host = config['default'].CONNECT_SSH
    ssh = conn_ssh(host)

    resultOut = ["[" + host[2] + "@" + host[0] + " ~]$ " + str(command[0])]
    ssh.exec_command(str(command[0]))

    resultOut.append("[" + host[2] + "@" + host[0] + " ~]$ " + str(command[1]))
    stdoutStr, sterrStr = get_exec_result(ssh, str(command[1]))
    if stdoutStr.strip():
        result = stdoutStr
    elif sterrStr.strip():
        result = sterrStr
    else:
        result = stdoutStr + sterrStr

    resultOut.append(result)
    close_ssh(ssh)
    return resultOut


# 积分计算结果验证
def SocreCalcStartCalc(command):

    # 连接主机
    host = config['default'].CONNECT_SSH
    ssh = conn_ssh(host)
    
    resultOut = []
    for i in range(0, 4):
        resultOut.append("[" + host[2] + "@" + host[0] + " ~]$ " + str(command[i][0]))
        ssh.exec_command(str(command[i][0]))  # cd

        resultOut.append("[" + host[2] + "@" + host[0] + " ~]$ " + str(command[i][1]))
        stdoutStr, sterrStr = get_exec_result(ssh, str(command[i][1]))  # ls
        if stdoutStr.strip():
            result = stdoutStr
        elif sterrStr.strip():
            result = sterrStr
        else:
            result = stdoutStr + sterrStr

        resultOut.append(result)
    close_ssh(ssh)
    return resultOut
